package com.twan.kotlinbase.pop

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.core.BottomPopupView
import com.twan.kotlinbase.BuildConfig
import com.twan.kotlinbase.R
import com.twan.kotlinbase.event.TakePhotoEvent
import com.twan.kotlinbase.util.RxPermissionsUtil
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.pop_add_pic.view.*
import org.greenrobot.eventbus.EventBus

class AddPicPopup(context: Activity,var fragment : Fragment?=null, maxSelect:Int=1, var isTakePhoto:Boolean =true,
                  var mimeType: Set<MimeType> = MimeType.ofImage()) : BottomPopupView(context) {
    companion object {
        val REQUEST_CODE_CHOOSE = 1001
        val REQUEST_CODE_TAKE_PHOTO = 1002
        val REQUEST_VIDEO_CAPTURE = 1003 //拍摄视频
    }

    private var mContext = context
    private var mMaxSelect = maxSelect
    override fun getImplLayoutId(): Int {
        return R.layout.pop_add_pic
    }

    override fun onCreate() {
        super.onCreate()

        btn_cancle.setOnClickListener { this@AddPicPopup.dismiss() }
        tv_gallery.setOnClickListener {
            RxPermissionsUtil.requestPermission(mContext as FragmentActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA) {
                var matisse = if (fragment !=null) {
                    Matisse.from(fragment)
                } else {
                    Matisse.from(mContext)
                }
                matisse.choose(mimeType)
                    .capture(false)
                    .captureStrategy(CaptureStrategy(true,"${BuildConfig.APPLICATION_ID}.fileprovider"))
                    .countable(true)
                    .maxSelectable(mMaxSelect)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(GlideEngine())
                    .showPreview(false) // Default is `true`
                    .showSingleMediaType(true)
                    .forResult(REQUEST_CODE_CHOOSE)
            }
            this@AddPicPopup.dismiss()
        }
        tv_take_photo.setOnClickListener {
            if (isTakePhoto) takePhoto() else takeVideo()
            this@AddPicPopup.dismiss()
        }


    }

    //拍照
    private fun takePhoto() {
        RxPermissionsUtil.requestPermission(mContext as FragmentActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA) {
            var takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(mContext.packageManager) != null) {
                var currPath= context.filesDir.path+ "/" + System.currentTimeMillis() + ".jpg"
                //var currPath = Environment.getExternalStorageDirectory().path + "/" + System.currentTimeMillis() + ".jpg"
                LogUtils.e("路径:$currPath")
                var iscreated = FileUtils.createFileByDeleteOldFile(currPath)
                var photoFile = FileUtils.getFileByPath(currPath)
                var photoURI = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", photoFile)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) //指定了存储的路径的uri,intent返回的data就为null,这是一种通用做法,适配各类机型
                mContext!!.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, photoURI))//通知到系统相册,不起作用
                if (fragment != null){
                    fragment!!.startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO)
                } else {
                    mContext.startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO)
                }
                EventBus.getDefault().post(TakePhotoEvent(currPath))
            }
        }
    }

    //录制视频
    private fun takeVideo() {
        RxPermissionsUtil.requestPermission(mContext as FragmentActivity, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) {
            var takeVideoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
            if (takeVideoIntent.resolveActivity(mContext.packageManager) != null) {
                var currPath= context.filesDir.path+ "/" + System.currentTimeMillis() + ".mp4"
                //var currPath = Environment.getExternalStorageDirectory().path + "/" + System.currentTimeMillis() + ".mp4"
                LogUtils.e("视频路径:$currPath")
                var iscreated = FileUtils.createFileByDeleteOldFile(currPath)
                var videoFile = FileUtils.getFileByPath(currPath)
                var videoURI = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", videoFile)
                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoURI) //指定了存储的路径的uri,intent返回的data就为null,这是一种通用做法,适配各类机型
                mContext!!.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,videoURI))//通知到系统相册
                if (fragment != null){
                    fragment!!.startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE)
                } else {
                    mContext.startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE)
                }
                EventBus.getDefault().post(TakePhotoEvent(currPath))
            }
        }
    }



}